
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { Observable, empty } from 'rxjs';
import { switchMapTo } from 'rxjs/operators';
import { environment } from '../environments/environment';


import { User } from '../models/User';

@Injectable()
export class UserService {


  private baseUrl = environment.apiUrl + 'api/user';


  constructor(
        private http: HttpClient
    ) {
  }

  getAllUsers(): Observable<{res: User[], success: boolean, total: number}> {
    return this.http.get<{res: User[], success: boolean, total: number}>(`${this.baseUrl}/getlist`);
  }

  getUsers(current: number = 1, pageSize: number = environment.pageSize, departmentId?: number): Observable<{res: User[], success: boolean, total: number}> {
    let params: HttpParams = new HttpParams();
    params = params.append('page', String(current));
    params = params.append('pageSize', String(pageSize));
    if (departmentId) {
      params = params.append('departmentId', String(departmentId));
    }
    return this.http.get<{res: User[], success: boolean, total: number}>(`${this.baseUrl}/getlist`, { params : params});
  }

    getUser(id: string): Observable<{res: User, success: boolean}> {
        return this.http.get<{res: User, success: boolean}>( `${this.baseUrl}/${id}`);
    }

    update(user: User): Observable<{res: User, success: boolean}> {
        const url = `${this.baseUrl}/update`;
        return this.http
            .post<{res: User, success: boolean}>(url, user);
    }
    changePassword(user: User): Observable<{res: User, success: boolean}>{
      return this.http.post<{ res: User, success: boolean }>(`${this.baseUrl}/updatepassword`, user);
    }
    register(user: User): Observable<{success: boolean, res: User}> {
        return this.http
            .post<{success: boolean, res: User}>(`${this.baseUrl}/insert`, user);
    }

    isExist(username: string): Observable<{success: boolean}> {
        return this.http
            .get<{success: boolean}>(`${this.baseUrl}/checkusername?username=${username}`);
    }

    del(id: number): Observable<{success: boolean}> {
        const url = `${this.baseUrl}/del/${id}`;
        return this.http.post<{success: boolean}>(url, {});
    }


}
